package servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mysql.cj.Session;
import pojo.Book;
import dao.BookDAO;

@WebServlet("/book")
public class BookListServlet extends HttpServlet {

    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html; charset=UTF-8");

        //截取关键字
        String keyword;
        if (request.getParameter("keyword") == null){
            keyword = "default";
        } else {
            keyword = request.getParameter("keyword");
        }
        request.setAttribute("keyword", keyword);

        //截取类别
        String category;
        if (request.getParameter("category") == null){
            category = "default";
        } else {
            category = request.getParameter("category");
        }
        request.setAttribute("bookcategory", category);

        //截取页码
        int start = 0;
        int count = 15;
        try {
            start = Integer.parseInt(request.getParameter("start"));
        } catch (NumberFormatException e) {
            // 当浏览器没有传参数start时
            start = 0;
        }

        //计数
        int next = start + count;
        int pre = start - count;

        int total = new BookDAO().getTotal();

        int last;
        if (0 == total % count)
            last = total - count;
        else
            last = total - total % count;

        pre = pre < 0 ? 0 : pre;
        next = next > last ? last : next;

        request.setAttribute("next", next);
        request.setAttribute("pre", pre);
        request.setAttribute("last", last);

        List<Book> books;
        if ("default".equals(category)) {
            if ("default".equals(keyword)) {
                books = new BookDAO().list(start, count);
            } else {
                books = new BookDAO().listByKey(start, count, keyword);
            }
        } else {
            if ("default".equals(keyword)) {
                books = new BookDAO().listByCat(start, count, category);
            } else {
                books = new BookDAO().list(start, count, category, keyword);
            }
        }
        request.setAttribute("books", books);

        request.getRequestDispatcher("listBook.jsp").forward(request, response);
    }
}